package com.news.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.news.bean.News;
import com.news.dao.NewsDao;
import com.news.dao.impl.NewsDaoImpl;
import com.news.util.NewsConfig;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.UUID;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class NewsServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        this.doPost(req, resp);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        News news = new News();
        NewsDao nd = new NewsDaoImpl();

        LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();


        String cmd = req.getParameter("cmd");//请求名称
        String id = "0";//("id");
        String title;
        String pic;
        String sort;
        String writer;
        String dates;
        String shows;
        String hits;//("hits");
        String message;
        String keyword = req.getParameter("keyword");
        ;


        try {
            // Check that we have a file upload request
            boolean isMultipart = ServletFileUpload.isMultipartContent(req);
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("UTF-8");
            if (isMultipart) {
                // Parse the request
                List items = upload.parseRequest(req); /* FileItem */

                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField()) {
                        String UTF = item.getString("UTF-8");
                        map.put(item.getFieldName(), UTF);
                    } else {
                        String path = this.getServletContext().getRealPath("/")+NewsConfig.newPicFolder;;
                        String file = item.getName();
                        String type = null;
                        if (file.lastIndexOf(".") > 0) {
                            type = file.substring(file.lastIndexOf("."));
                        }
                        String uuid = UUID.randomUUID().toString();
                        file = uuid + type;
                        path += file;
                        File tmppic = new File(path);
                        if (!tmppic.getParentFile().exists()) {
                            tmppic.getParentFile().mkdirs();
                        }
                        FileOutputStream fos=new FileOutputStream(tmppic);
                        byte[] b = item.get();
                        fos.write(b);
                        fos.flush();
                        fos.close();
                        map.put("picfile", b);
                        map.put("pic", NewsConfig.newPicFolder+file);
                    }
                }
                System.out.println("map is " + map.toString());
                news.init(map);
                id = map.get("id") == null ? "0" : map.get("id").toString();
            } else {
                id = req.getParameter("id");//("id");
                title = req.getParameter("title");
                pic = req.getParameter("pic");
                sort = req.getParameter("sort");
                int sortInt = Integer.parseInt(sort == null ? "0" : sort);
                writer = req.getParameter("writer");
                dates = req.getParameter("dates");
                shows = req.getParameter("shows");
                hits = req.getParameter("hits");//("hits");
                message = req.getParameter("message");
                keyword = req.getParameter("keyword");
                if (id != null) {
                    news.setId(Integer.valueOf(id));
                }
                news.setTitle(title);
                news.setPic(pic);
                news.setSort(sortInt);
                news.setWriter(writer);
                news.setDates(dates);
                news.setShows(shows);
                if (hits != null) {
                    news.setHits(Integer.valueOf(hits));
                }
                news.setMessage(message);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }


        if (cmd != null) {
            if (cmd.equals("list")) {	//显示列表(暂时无分页)
                List<News> list = nd.list(new HashMap<String, String>());
                req.setAttribute("list", list);
                req.getRequestDispatcher("newsList.jsp").forward(req, resp);
            }
            if (cmd.equals("add")) {	//添加
                nd.add(news);
                System.out.println("************************************** " + news.getSort());
                resp.sendRedirect("news?cmd=list");
            }
            if (cmd.equals("edit")) {	//修改
                nd.edit(news);
                resp.sendRedirect("news?cmd=list&id=" + id);
            }
            if (cmd.equals("del")) {	//删除

                //多选删除功能
                String[] vals = req.getParameterValues("id");
                if (vals.length > 1) {
                    for (int i = 0; i < vals.length; i++) {
                        nd.delete(Integer.valueOf(vals[i]));
                    }
                    return;
                }


                nd.delete(Integer.valueOf(id));
                //req.getRequestDispatcher("newsList.jsp").forward(req,resp);
                resp.sendRedirect("news?cmd=list");
            }
            if (cmd.equals("get")) {	//获取信息
                nd.get(Integer.valueOf(id));
                //req.getRequestDispatcher("newsList.jsp").forward(req,resp);
                resp.sendRedirect("news?cmd=list&id=" + id);
            }
            if (cmd.equals("loadedit")) {
                News ne = nd.get(Integer.valueOf(id));
                req.setAttribute("ne", ne);
                req.getRequestDispatcher("newsEdit.jsp").forward(req, resp);

            }
            if (cmd.equals("listbykey")) {
                System.out.println("keyword" + keyword);
                System.out.println("zzzzzzzzzz");
                System.out.println("===================================");
                List<News> listtype = nd.ListByKeyWord(keyword);
                req.setAttribute("listbykey", listtype);
                req.setAttribute("key", keyword);
                // window.parent.main.location='http://localhost:8080/HBLPro/display/newsTypeList.jsp'
                req.getRequestDispatcher("display/newsTypeList.jsp").forward(req, resp);
            }

        }
    }
}
